package com.itheima.demo6copy;

import java.io.*;

public class Copy2 {
    public static void main(String[] args) throws Exception{
        String srcPath="C:\\Users\\ASUS\\Desktop\\演示文稿1(1).jpg";
        String destPath="E:\\learn\\新建文件夹\\新建文件夹 (2)\\演示文稿1(1).jpg";
        copy(srcPath,destPath);
    }
    public static void copy(String srcPath,String destPath) {
        OutputStream os = null;
        InputStream is = null;
        try {
            //        目标使用字节流实现问价的复制操作
            is = new FileInputStream(srcPath);
            os = new FileOutputStream(destPath);
            byte[] buffer = new byte[1024];
//        定义一个变量记住每次读取的字节个数
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);// 把每次读取的字节数组，写入到目标文件。
            }
            System.out.println("复制完成");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//            最后一定执行一次，即便程序出现异常
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
